/**
 * 
 */
package com.placement.app.service;

import java.util.ArrayList;
import java.util.StringTokenizer;

import com.placement.app.dao.LocationHelperDAO;
import com.placement.app.model.Address;
import com.placement.app.model.ZipLocation;
import com.placement.app.util.AddressLookup;

/**
 * @author ns_nagar
 *
 */
public class LocationServiceImpl implements LocationService {
	
	private LocationHelperDAO locationHelperDAO;
	/* (non-Javadoc)
	 * This process converts valid address to zip code.
	 * @see com.placement.app.service.LocationService#getZipCode(com.placement.app.model.Address)
	 */
	public ZipLocation getZipCode(Address address) {
		
		return locationHelperDAO.getZipCode(address);
	}

	/* (non-Javadoc)
	 * @see com.placement.app.service.LocationService#getZipCodeByDistance(int, int)
	 */
	public ArrayList<String> getZipCodeByDistance(int zipcode, int distance) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.placement.app.service.LocationService#isvalidZipCode(int)
	 */
	public boolean isvalidZipCode(int zipcode) {
		// TODO Auto-generated method stub
		return false;
	}

	public ZipLocation getLocation(String location) {
		if(location == null || location.length() == 0)
			// Can not pass null or blank
			return new ZipLocation();
		String locStr = location.replaceAll("[\\W&&[^\\s]]", "");
		String[] addresses = locStr.split(" ");
		if(addresses.length==1){
			char[] arr = addresses[0].toCharArray();
			if (arr.length == 5) {
				boolean isZipcode = true;
				for (char c : arr) {
					if (!Character.isDigit(c))
						isZipcode = false;
				}
				if(isZipcode)
					return getZipLocation(Long.parseLong(location));
			}
		}
		String state = addresses[addresses.length-1];
		String foundState = "";
		if(state.length()!= 2){
			foundState = AddressLookup.matchState(state);
		} else 
			foundState = state;
		String city = "";
		for (int i = 0; i < (addresses.length -1); i++) {
			city = addresses[i] + " ";
		}
		String foundCity = AddressLookup.matchCity(city.trim());
		Address add = new Address();
		add.setCity(foundCity);
		add.setState(foundState);
		ZipLocation code = getZipCode(add);
		//if (code != null)
		//	return  code;
		return code;
	}

	private ZipLocation getZipLocation(Long location) {
		// TODO Auto-generated method stub
		return locationHelperDAO.getZiplocationByCode(location);
	}

	public LocationHelperDAO getLocationHelperDAO() {
		return locationHelperDAO;
	}

	public void setLocationHelperDAO(LocationHelperDAO locationHelperDAOImpl) {
		this.locationHelperDAO = locationHelperDAOImpl;
	}

	public ArrayList<ZipLocation> getZipCodesInRange(ZipLocation loc, int range) {
		// TODO Auto-generated method stub
		return null;
	}

}
